class MyPageHeader extends BaseEditMaster {
    constructor(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
            returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl) {
        super(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
                returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl);
        this.hasFilterValue = true;
        this.checkUrl = "/purchase/po/header/check.html";
        this.uncheckUrl = "/purchase/po/header/uncheck.html";
    }
    OnPageLoad() {
        super.OnPageLoad();
        // 根据输入的供应商编号，设置相应的供应商信息
        $('#SupplierNo').keyup((event) => {
            if (parseInt(event.keyCode) === 13) {
                let index = $(":input").index(this);
                let _params = {};
                _params['SupplierNo'] = $.trim($('#SupplierNo').val());
                super.DoAjax(_params, "/master/supplier/fetchByNo.html", function (data, $self) {
                    $("#SupplierId").val(data.supplierId === null ? "" : data.supplierId);
                    $("#SupplierName").val(data.supplierName === null ? "" : data.supplierName);
                    $("#SupplierNo").val(data.supplierNo === null ? "" : data.supplierNo);
                    $("#Attn").val(data.attn === null ? "" : data.attn);
                    $("#Fax").val(data.fax === null ? "" : data.fax);
                    // 焦点移动到下一个文本框
                    if (data.supplierId !== null) {
                        let newIndex = index + 1;
                        $(":input:eq(" + newIndex + ")").focus();
                    }
                });
            }
        });
    }
    GetFilterValue() {
        let item = {};
        item['HeaderId'] = parseInt(this.dataId);
        item['CurrentUserId'] = parseInt($("#UserId").val());
        item['WorkFlowId'] = $("#WorkFlowId").val() === '' ? 0 : parseInt($("#WorkFlowId").val());
        item['PageIndex'] = 1;
        item['Flag'] = 1;    // 表示要读取包括调达表等其他信息
        item['Limit02'] = parseInt($("#page-size_02").val());
        item['Limit03'] = parseInt($("#page-size_03").val());
        item['Limit'] = parseInt($("#page-size_04").val());

        return item;
    }
    // 得到主表数据
    GetEntityData() {
        let item = {};
        item['headerId'] = $("#HeaderId").val();
        item['enterpriseId'] = $("#EnterpriseId").val();
        item['billTypeId'] = $("#BillTypeId").val();    // 采购类型
        item['poNo'] = $.trim($("#PoNo").val());
        item['supplierId'] = formatNullInputValue($.trim($("#SupplierId").val()));
        item['supplierName'] = formatNullInputValue($.trim($("#SupplierName").val()));
        item['attn'] = formatNullInputValue($.trim($("#Attn").val()));
        item['fax'] = formatNullInputValue($.trim($("#Fax").val()));
        item['signedDate'] = formatNullInputValue($.trim($("#SignedDate").val()));
        item['orderArrivalDate'] = formatNullInputValue($.trim($("#OrderArrivalDate").val()));
        item['currencyId'] = formatNullInputValue($.trim($("#CurrencyId").val()));
        item['currencyName'] = formatNullInputValue($.trim($("#CurrencyName").val()));
        item['taxRateId'] = formatNullInputValue($.trim($("#TaxRateId").val()));
        item['freightFlag'] = $("#FreightFlag").is(":checked") ? true : false;   // 是否包运费
        item['fabricWidth'] = formatNullInputValue($.trim($("#FabricWidth").val()));
        item['gramWeight'] = formatNullInputValue($.trim($("#GramWeight").val()));
        item['quantityOfLimited'] = formatNullInputValue($.trim($("#QuantityOfLimited").val()));
        item['termsOfPayment'] = formatNullInputValue($.trim($("#TermsOfPayment").val()));
        item['performedPlace'] = formatNullInputValue($.trim($("#PerformedPlace").val()));
        item['purchasedBy'] = formatNullInputValue($.trim($("#PurchasedBy").val()));
        item['updatedBy'] = $.trim($("#UserId").val());
        item['updatedByName'] = $.trim($("#UserName").val());
        item['updatedDate'] = formatNullInputValue($.trim($("#UpdatedDate").val()));
        item['qualityStandard'] = formatNullInputValue($.trim($("#QualityStandard").html())); //formatNullInputValue($.trim($("#QualityStandard").val()));
        item['description'] = formatNullInputValue($.trim($("#Description").val()));
        item['createdBy'] = $.trim($("#UserId").val());
        item['updatedBy'] = $.trim($("#UserId").val());
        return JSON.stringify(item);
    }
    FillData(data) {
        let item = data.HeaderEntity;
        $("#HeaderId").val(item.headerId);
        //this.dataId = item.headerId;
        $("#PoNo").val(item.poNo);
        $("#BillTypeId").val(item.billTypeId);   // 合同类型
        $("#SupplierId").val(item.supplierId);
        $("#SupplierNo").val(item.supplierNo);
        $("#SupplierName").val(item.supplierName);
        $("#Attn").val(item.attn);
        $("#Fax").val(item.fax);
        $("#CurrencyId").val(item.currencyId);
        $("#CurrencyName").val(item.currencyName);
        $("#TaxRateId").val(item.taxRateId);
        $("#TaxRateText").val(item.taxRateText);
        // 是否包含运费
        if (item.freightFlag === true) {
            $("#FreightFlag").prop("checked", true);
        } else {
            $("#FreightFlag").prop("checked", false);
        }
        $("#SignedDate").val(item.signedDate);
        $("#OrderArrivalDate").val(item.orderArrivalDate);
        $("#FabricWidth").val(item.fabricWidth);
        $("#GramWeight").val(item.gramWeight);
        $("#QuantityOfLimited").val(item.quantityOfLimited);
        $("#TermsOfPayment").val(item.termsOfPayment);
        $("#QualityStandard").html(item.qualityStandard);
        $("#Description").val(item.description);
        $("#PerformedPlace").val(item.performedPlace);
        $("#PurchasedBy").val(item.purchasedBy);
        $("#PurchasedByName").val(item.purchasedByName);
        $("#UpdatedBy").val(item.updatedBy);
        $("#UpdatedByName").val(item.updatedByName);
        $("#UpdatedDate").val(item.updatedDate);

        // 最后的审核人、审核日期
        $("#CheckedBy").val(item.checkedBy);
        $("#CheckedByName").val(item.checkedByName);
        $("#CheckedDate").val(item.checkedDate === null ? '' : item.checkedDate);
        $("#CheckedStatus").val(item.checkedStatus);
        $('#FlowOrderNo').val(item.flowOrderNo);

        // 设置用于控制的用户ID
        this.privateUserId = $("#PurchasedBy").val();

        // 引入的调达表列表
        _InstancePageLinesMrpHeader.BuildDataTable(data.LinesMrpList);
        // 引入的调达表明细列表           
        _InstancePageLinesMrpLines.BuildDataTable(data.LinesMrpLinesList);
        // 引入的补料单
        _InstancePageLinesMrpFeedingHeader.BuildDataTable(data.LinesMrpFeedingList);
        // 引入的补料单明细列表           
        _InstancePageLinesMrpFeedingLines.BuildDataTable(data.LinesMrpFeedingLinesList);
        // 设置订单的材料列表
        _InstancePageLines.SetPoMaterialList(data.PoMaterialList);
        // 合同明细表             
        _InstancePageLines.BuildDataTable(data.PoLinesList);

        this.currentTaskPrivileges = item.currentTaskPrivileges;
        this.nextTaskPrivileges = item.nextTaskPrivileges;
        this.unCheckFlag = item.unCheckFlag;

        this.SetPageElementStatus(this.HidePageElement, this.ShowPageElement, function () {
        });
        $("#PoNo").focus();
    }
    Save() {
        super.Save(function (data, _this) {
            if (data > 0) {
                if (parseInt(_this.pageStatus) === 1) {
                    $("#HeaderId").val(data);   // 设置刚才插入的记录ID
                    _this.dataId = data;
                    $("#Action").val(2);
                    _this.pageStatus = 2;
                    $("#menu_02").show();
                    $("#menu_03").show();
                    $("#menu_04").show();

                    $("#ButPrint").show();
                    $("#ButExport").show();
                    $("#CheckedTip").removeClass().addClass("huzo_status").addClass("huzo_status__red");
                    $("#CheckedTip").html("状态：未审核");
                    $("#CheckedTip").show();
                } else {
                    // 如果是更新状态，则更新主表后同时刷新订单明细页（因为有可能有数据的供应商不一致的情况）
                    let _pageIndex = $("abbr.page_indicator_block,#wrapper__navbar_04").attr("_msh_page");
                    _InstancePageLines.FetchLinesForPage(_pageIndex);
                }
            }
        });
    }
    New() {
        super.New();
        $("#HeaderId").val(0);
        $("#BillType").val("-1");
        $("#TermsOfPayment").val("月结");
        this.FetchNewBillNo();        // 设置新的单据号
        this.FetchLocalCurrency();    // 设置本币信息
        this.FetchCurrenctTaxRate();  // 设置当前税率

        // 默认设置一些值
        $("#UpdatedBy").val($("#UserId").val());
        $("#UpdatedByName").val($("#UserName").val());
        $("#UpdatedDate").val(getCurrentDate());
        $("#PurchasedBy").val($("#UserId").val());
        $("#PurchasedByName").val($("#UserName").val());
        $("#SignedDate").val(getCurrentDate());        // 落单日期
        $("#QualityStandard").html("");
        $("#FreightFlag").prop("checked", true);

        $("#ButExport").hide();   // 隐藏导出按钮

        $("#menu_02").hide();
        $("#menu_03").hide();
        $("#menu_04").hide();

        // 清空明细内容
        $("#tabMrpListData tbody").empty();
        $("#tabData21 tbody").empty();
        $("#tabData22 tbody").empty();
        $("#tabData31 tbody").empty();
        $("#tabData32 tbody").empty();
        $("#tabData41 tbody").empty();
        $("#tabData42 tbody").empty();
        // 设置按钮可见
        $("#ButBatchDeleteMdpLines").show();
        $("#ButUpdateRowMaterialNo").show();
        $("#ButSetRowMaterialLossType").show();
        $("#ButAddSurCharges").show();
        $("#ButBatchCleanLoss").show();
        $("#ButSaveLines").show();

        //$("abbr.page_indicator_block,#wrapper__navbar_02").attr("_msh_page", 1);
        //$("abbr.page_indicator_block,#wrapper__navbar_03").attr("_msh_page", 1);
        //$("abbr.page_indicator_block,#wrapper__navbar_04").attr("_msh_page", 1);

        $("#PoNo").focus();
    }
    // 设置本币信息
    FetchLocalCurrency() {
        super.DoAjax({}, "/master/currency/fetchLocalCurrency.html", function (data, _this) {
            if (data !== null) {
                $("#CurrencyId").val(data.currencyId);
                $("#CurrencyName").val(data.currencyName);
            } else {
                ShowErrorMessagePanel('本币信息获取失败。');
            }
        });
    }
    // 设置当前税率
    FetchCurrenctTaxRate() {
        super.DoAjax({}, "/master/tax_rate/fetchCurrentTaxRate.html", function (data, _this) {
            if (data !== null) {
                $("#TaxRateId").val(data.taxRateId);
                $("#TaxRateText").val(data.taxRateText);
            } else {
                ShowErrorMessagePanel('当前税率获取失败。');
            }
        });
    }
    // 自动设置设置新的单据号
    FetchNewBillNo() {
        super.DoAjax({}, "/purchase/po/header/fetchNewNoOfBill.html", function (data, _this) {
            $("#PoNo").val(data.NoOfBill);
        });
    }
    // 以下为选择框
    DoCleanInpStandard() {
        $("#QualityStandard").html("");
    }
    DoChoiceInpStandard() {
        let _choice = new CommonChoice();
        _choice.DoChoiceInpStandard(0, '选择化检标准', (data) => {
            if (data) {
                // 判断是否数据发生了改变如果改变则设置改变标记
                if ($("#QualityStandard").html() !== data[1]) {
                    $("#form_data").data("changed", true);
                }
                $("#QualityStandard").html(data[1]);
                //$("#QualityStandard").focus();
            }
        });
        //$("#QualityStandard").focus();
    }
    DoChoiceQuantityOfLimited() {
        let _choice = new CommonChoice();
        _choice.DoChoiceQuantityOfLimited(1, '选择化检标准', (data) => {
            if (data) {
                let _result = "";
                for (let i = 0; i < data.length; i++) {
                    _result += data[i]['QuantityOfLimited'] + "\n";
                }
                // 判断是否数据发生了改变如果改变则设置改变标记
                if ($("#QuantityOfLimited").val() !== _result) {
                    $("#form_data").data("changed", true);
                }
                $("#QuantityOfLimited").val(_result);
                $("#QuantityOfLimited").focus();
            }
        });
        $("#QuantityOfLimited").focus();
    }
    DoChoicePerformedPlace() {
        let _choice = new CommonChoice();
        _choice.DoChoiceDeliveryAddress(0, '选择交货地址', (data) => {
            if (data) {
                // 判断是否数据发生了改变如果改变则设置改变标记
                if ($("#PerformedPlace").val() !== data[1]) {
                    $("#form_data").data("changed", true);
                }
                $("#PerformedPlace").val(data[1]);
                $("#PerformedPlace").focus();
            }
        });
        $("#PerformedPlace").focus();
    }
    DoChoiceSupplier() {
        let _choice = new CommonChoice();
        let params = {};
        params['Flag'] = 0;
        params['CurrentUserId'] = null;
        params['NotInGroupId'] = null;
        _choice.DoChoiceSupplier(params, '选择供应商', (data) => {
            if (data) {
                // 判断是否数据发生了改变如果改变则设置改变标记
                if ($("#SupplierName").val() !== data[1]) {
                    $("#form_data").data("changed", true);
                }
                $("#SupplierId").val(data[0]);
                $("#SupplierNo").val(data[4]);
                $("#SupplierName").val(data[1]);
                $("#Attn").val(data[2]);
                $("#Fax").val(data[3]);
                $("#SupplierName").focus();
            }
        });
        $("#SupplierName").focus();
    }
    DoChoiceCurrency() {
        let _choice = new CommonChoice();
        _choice.DoChoiceCurrency(0, (data) => {
            if (data) {
                // 判断是否数据发生了改变如果改变则设置改变标记
                if ($("#CurrencyName").val() !== data[1]) {
                    $("#form_data").data("changed", true);
                }
                $("#CurrencyId").val(data[0]);
                $("#CurrencyName").val(data[1]);
                $("#CurrencyName").focus();
            }
        });
        $("#CurrencyName").focus();
    }
    DoChoiceTaxRate() {
        let _choice = new CommonChoice();
        _choice.DoChoiceTaxRate(0, (data) => {
            if (data) {
                // 判断是否数据发生了改变如果改变则设置改变标记
                if ($("#TaxRateText").val() !== data[2]) {
                    $("#form_data").data("changed", true);
                }
                $("#TaxRateId").val(data[0]);
                $("#TaxRateText").val(data[2]);
                $("#TaxRateText").focus();
            }
        });
        $("#CurrencyName").focus();
    }
    DoChoicePurchasedBy() {
        // 只有登录者=采购担当 才可以操作，否则废除错误提示
        if (parseInt($("#UserId").val()) !== parseInt($("#PurchasedBy").val())) {
            if ($("#RoleName").val().indexOf("系统管理员") === -1) {
                ShowErrorMessagePanel('错误提示：您不是采购担当，无法进行操作。');
                return false;
            }
        }
        let _choice = new CommonChoice();
        _choice.DoChoiceUser(0, '选择采购担当', '采购', (data) => {
            if (data) {
                // 判断是否数据发生了改变如果改变则设置改变标记
                if ($("#PurchasedByName").val() !== data[1]) {
                    $("#form_data").data("changed", true);
                }
                $("#PurchasedBy").val(data[0]);
                $("#PurchasedByName").val(data[1]);
                $("#PurchasedByName").focus();
            }
        });
        $("#PurchasedByName").focus();
    }
    DoChoiceTermsOfPayment() {
        let _choice = new CommonChoice();
        _choice.DoChoiceSettlementMode(0, (data) => {
            if (data) {
                // 判断是否数据发生了改变如果改变则设置改变标记
                if ($("#TermsOfPayment").val() !== data[1]) {
                    $("#form_data").data("changed", true);
                }
                $("#TermsOfPayment").val(data[1]);
                $("#TermsOfPayment").focus();
            }
        });
        $("#TermsOfPayment").focus();
    }
    // 导出到Excel
    ExportMemo() {
        $("#export_form").attr("action", parent.basePath + "/purchase/po/export_memo_to_excel.html");
        $("#ExportPoHeaderId").val($("#HeaderId").val());
        $("#export_form").submit();
    }
    DoPrintPreview() {
        window.open(parent.basePath + this.printUrl + "?id=" + $("#HeaderId").val() + "&currentUserId=" + $("#UserId").val());
    }
    DoCheck() {
        let item = {};
        item['HeaderId'] = parseInt($("#HeaderId").val());
        item['WorkFlowId'] = parseInt($("#WorkFlowId").val());
        item['NodeOrder'] = parseInt($("#FlowOrderNo").val());
        item['CheckedBy'] = parseInt($("#UserId").val());
        item['IsCheckCurrentNode'] = this.currentTaskPrivileges === 0 ? 0 : 1;
        item['PageIndex'] = $("abbr.page_indicator_block,#wrapper__navbar_04").attr("_msh_page");
        item['Limit'] = parseInt($("#page-size_04").val());

        $.ajax({
            type: "POST",
            url: parent.basePath + this.checkUrl,
            timeout: 30 * 1000,
            data: JSON.stringify(item),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: () => {
            }
        }).done(data => {
            let item = data.HeaderEntity;
            // 最后的审核人、审核日期
            $("#CheckedBy").val(item.checkedBy);
            $("#CheckedByName").val(item.checkedByName);
            $("#CheckedDate").val(item.checkedDate === null ? '' : item.checkedDate);
            $("#CheckedStatus").val(item.checkedStatus);
            $('#FlowOrderNo').val(item.flowOrderNo);
            // 合同明细表             
            _InstancePageLines.BuildDataTable(data.PoLinesList);
            this.currentTaskPrivileges = item.currentTaskPrivileges;
            this.nextTaskPrivileges = item.nextTaskPrivileges;
            this.unCheckFlag = item.unCheckFlag;

            // 设置画面各个元素状态
            this.SetPageElementStatus(this.HidePageElement, this.ShowPageElement, function () {
            });
        }).fail(function (data) {
            ajaxError(data, 1);
        }).always(function ( ) {
        });
    }
    Uncheck() {
        let item = {};
        item['HeaderId'] = parseInt($("#HeaderId").val());
        item['WorkFlowId'] = parseInt($("#WorkFlowId").val());
        item['NodeOrder'] = parseInt($("#FlowOrderNo").val());
        item['CheckedBy'] = parseInt($("#UserId").val());
        item['PageIndex'] = $("abbr.page_indicator_block,#wrapper__navbar_04").attr("_msh_page");
        item['Limit'] = parseInt($("#page-size_04").val());

        $.ajax({
            type: "POST",
            url: parent.basePath + this.uncheckUrl,
            timeout: 30 * 1000,
            data: JSON.stringify(item),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: () => {
            }
        }).done(data => {
            let item = data.HeaderEntity;
            // 最后的审核人、审核日期
            $("#CheckedBy").val(item.checkedBy);
            $("#CheckedByName").val(item.checkedByName);
            $("#CheckedDate").val(item.checkedDate === null ? '' : item.checkedDate);
            $("#CheckedStatus").val(item.checkedStatus);
            $('#FlowOrderNo').val(item.flowOrderNo);
            // 合同明细表             
            _InstancePageLines.BuildDataTable(data.PoLinesList);

            this.currentTaskPrivileges = item.currentTaskPrivileges;
            this.nextTaskPrivileges = item.nextTaskPrivileges;
            this.unCheckFlag = item.unCheckFlag;

            // 设置画面各个元素状态
            this.SetPageElementStatus(this.HidePageElement, this.ShowPageElement, function () {
            });
        }).fail(data => {
            ajaxError(data, 1);
        }).always(( ) => {
        });
    }
    ShowPageElement() {
        $("Button.act__save").show();
        if (!$("span.act__delete").hasClass("act__delete")) {
            $("span.act__delete").addClass("trash");
            $("span.act__delete i").addClass("fa-all fa-trash-o fa-1");
        }
        $("#search_btn_04").css("margin-left", "65px");
    }
    HidePageElement() {
        $("Button.act__save").hide();
        $("span.act__delete").removeClass("trash");
        $("span.act__delete i").removeClass("fa-all fa-trash-o fa-1");
        $("#search_btn_04").css("margin-left", "0px");
    }
}

//-----------------------------------------------------------------------------
// 引入的调达表
//-----------------------------------------------------------------------------
class MyPageLinesMrpHeader extends BaseEditSlave {
    constructor() {
        super('', '', '');
    }
    // 构建明细数据列表
    BuildDataTable(result) {
        $('#tabMrpListData tbody').empty();
        if (result === null)
            return false;
        let content_01 = '';
        let sequence = 1;
        for (let i = 0; i < result.length; i++) {
            let linesid = result[i].linesId;
            sequence = i + 1;
            content_01 += '<tr _mash_id="' + linesid + '">';
            content_01 += '<td style="text-align:center;">' + sequence + '</td>';
            content_01 += '<td>' + formatNullData(result[i].contractNo) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].styleNo) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].productName) + '</td>';
            content_01 += '<td style="text-align:center;">' + formatNullData(result[i].mrpTypeName) + '</td>';
            content_01 += '</tr>';
            $('#tabMrpListData tbody').append(content_01);
            content_01 = '';
        }
        setOneTableRowColor("tabMrpListData");
    }
    ImportMrp() {
        let _this = this;
        parent.showModal(1295, 630, '引入调达表',
                parent.basePath + '/tech/mrp_for_po/choice.html?isQuotedFlag=0&enterpriseId=' + $("#EnterpriseId").val(), null, ($dialog) => {
            let _exist = $.inArray($dialog, parent.arrDialog);
            if (_exist >= 0) {
                parent.arrDialog.splice($.inArray($dialog, parent.arrDialog), 1);
            }
            // 做选择设置
            if (parent.choice_success) {
                let MrpHeaderIdList = [];
                let MrpLinesIdList = [];
                for (let key in parent.arrChoice[0].SelectedHeaderList) {
                    MrpHeaderIdList.push(parseInt(key));
                }
                for (let key in parent.arrChoice[0].SelectedLinesList) {
                    MrpLinesIdList.push(key);
                }

                // 根据所选择的调达表，形成采购合同明细
                let _params = {};
                _params['HeaderId'] = parseInt($('#HeaderId').val());
                _params['CreatedBy'] = parseInt($("#UserId").val());
                _params['UpdatedBy'] = parseInt($("#UserId").val());
                _params['MrpHeaderId'] = MrpHeaderIdList;
                _params['MrpLinesId'] = MrpLinesIdList;
                _params['SeparateFlagByPartOfNeed'] = parseInt(parent.arrChoice[0].SeparateFlagByPartOfNeed);
                _params['SelectAllFlag'] = parseInt(parent.arrChoice[0].SelectAllFlag);
                _params['StyleNoFilterValue'] = parent.arrChoice[0].StyleNoFilterValue;
                _params['MaterialNoFilterValue'] = parent.arrChoice[0].MaterialNoFilterValue;
                _params['MaterialNameFilterValue'] = parent.arrChoice[0].MaterialNameFilterValue;
                _params['SupplierNameFilterValue'] = parent.arrChoice[0].SupplierNameFilterValue;
                _params['Limit02'] = parseInt($("#page-size_02").val());
                _params['Limit03'] = parseInt($("#page-size_03").val());
                _params['Limit04'] = parseInt($("#page-size_04").val());
                _params['PoNo'] = $("#PoNo").val();

                $.ajax({
                    type: "POST",
                    url: parent.basePath + "/purchase/po/lines/mrp/insert.html",
                    timeout: 60 * 1000,
                    data: JSON.stringify(_params),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    beforeSend: function () {
                    }
                }).done((data) => {
                    // 引入的调达表列表
                    _this.BuildDataTable(data.LinesMrpList);
                    // 引入的调达表明细列表           
                    _InstancePageLinesMrpLines.BuildDataTable(data.LinesMrpLinesList);
                    // 设置订单的材料列表
                    _InstancePageLines.SetPoMaterialList(data.PoMaterialList);
                    // 合同明细表             
                    _InstancePageLines.BuildDataTable(data.PoLinesList);

                    ShowSuccessMessagePanel("引入调达表成功。");
                }).fail((data) => {
                    ajaxError(data, 1);
                }).always(( ) => {
                });
            }
            // 清空数组
            parent.arrChoice.splice(0, parent.arrChoice.length);
            parent.choice_success = false;
        });
    }
}

//-----------------------------------------------------------------------------
// 引入的调达表明细
//-----------------------------------------------------------------------------
class MyPageLinesMrpLines extends BaseEditSlave {
    constructor() {
        super('', '', '');
        this.orderby = "";
    }
    SetPageSize02() {
        $.cookie("po_list_mrp_lines_pagesize", $("#page-size_02").val());
        this.FetchLinesForPage(1);
    }
    // 获取明细表分页信息
    GetFilterValue(pageIndex) {
        if (pageIndex !== 0) {
            $("abbr.page_indicator_block,#wrapper__navbar_02").attr("_msh_page", pageIndex);
        }

        let item = {};
        item['HeaderId'] = parseInt($.trim($("#HeaderId").val()));
        item['CurrentUserId'] = parseInt($("#UserId").val());      // 当前操作者，用于过滤供应商分组
        item['Limit'] = parseInt($("#page-size_02").val());        // limit;
        item['PageIndex'] = parseInt($("abbr.page_indicator_block,#wrapper__navbar_02").attr("_msh_page"));
        item['OrderBy'] = this.orderby;

        item['StyleNoFilterValue'] = formatNullInputValue($.trim($("#StyleNoFilterValue_02").val()));
        item['MaterialNoFilterValue'] = formatNullInputValue($.trim($("#MaterialNoFilterValue_02").val()));
        item['MaterialNameFilterValue'] = formatNullInputValue($.trim($("#MaterialNameFilterValue_02").val()));
        item['MaterialColourNameFilterValue'] = formatNullInputValue($.trim($("#MaterialColourNameFilterValue_02").val()));

        return JSON.stringify(item);
    }
    FetchLinesForPageNoFilter() {
        $("#StyleNoFilterValue_02").val("");
        $("#MaterialNoFilterValue_02").val("");
        $("#MaterialNameFilterValue_02").val("");
        $("#MaterialColourNameFilterValue_02").val("");

        $("abbr.page_indicator_block,#wrapper__navbar_02").attr("_msh_page", 1);
        this.FetchLinesForPage(1);
    }
    // 取得引入的调达表明细分页信息
    FetchLinesForPage(pageIndex) {
        $.ajax({
            type: "POST",
            url: parent.basePath + "/purchase/po/lines/mrp/fetchForPage.html",
            timeout: 60 * 1000,
            data: this.GetFilterValue(pageIndex),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
                $("#loading__indicator_02 i").addClass("fa-spin");
                $("#loading__indicator_02").show();
            }
        }).done((data) => {
            this.BuildDataTable(data);
        }).fail((data) => {
            ajaxError(data, 1);
        }).always(() => {
            $("#loading__indicator_02 i").removeClass("fa-spin");
            $("#loading__indicator_02").hide();
        });
    }
    // 构建明细数据列表
    BuildDataTable(result) {
        $('#tabData21 tbody').empty();
        $('#tabData22 tbody').empty();

        if (result.Success === false) {
            return;
        }
        // 设置翻页控件
        if (result.TotalPages > 0) {  //总页数
            $("#wrapper__navbar_02").data("swPagination").options.max_page = result.TotalPages;
        } else {
            $("#wrapper__navbar_02").data("swPagination").options.max_page = 1;
        }
        if (result.PageIndex > 0) { //当前页数
            $("#wrapper__navbar_02").data("swPagination").options.current_page = result.PageIndex;
            $("#wrapper__navbar_02").data("swPagination").setPage(result.PageIndex);
        } else {
            $("#wrapper__navbar_02").data("swPagination").options.current_page = 1; //当前页数
            $("#wrapper__navbar_02").data("swPagination").setPage(1);
        }

        // 得到数据列表
        result = result.DataList;
        if (result === null) {
            return false;
        }
        let content_01 = '';
        let content_02 = '';
        for (let i = 0; i < result.length; i++) {
            let id = result[i].linesId;
            content_01 += '<tr _mash_id="' + id + '">';
            content_01 += '<td>' + formatNullData(result[i].contractNo) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].styleNo) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].destination) + '</td>';                     // 发货目的地
            content_01 += '<td _mash_materialId="' + result[i].materialId + '">' + formatNullData(result[i].materialName) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].materialCode) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].supplierName) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].partOfNeed) + '</td>';
            content_01 += '</tr>';

            content_02 += '<tr>';
            content_02 += '<td>' + formatNullData(result[i].productColourName) + '</td>';                                          // 成品色
            content_02 += '<td style="text-align:center;">' + formatNullData(result[i].productSizeName) + '</td>';                 // 成品码
            content_02 += '<td>' + formatNullData(result[i].materialColourName) + '</td>';                                         // 材料色
            content_02 += '<td>' + formatNullData(result[i].fabricWidth) + '</td>';                                                // 净幅
            content_02 += '<td>' + formatNullData(result[i].specification) + '</td>';                                              // 规格即毛幅
            content_02 += '<td>' + formatNullData(result[i].factoryPieceYardage === 0 ? null : result[i].factoryPieceYardage) + '</td>';     // 工厂用量
            content_02 += '<td>' + formatNullData(result[i].suitCutPieceYardage === 0 ? null : result[i].suitCutPieceYardage) + '</td>';     // 套裁量
            content_02 += '<td style="text-align:center;">' + formatNullData(result[i].uomName) + '</td>';                         // 单位
            content_02 += '<td>' + formatNullData(result[i].quantityOfProduct) + '</td>';                                          // 成品数量
            content_02 += '<td>' + (result[i].factoryPieceYardage * result[i].productQuantity).toFixed(2) + '</td>';               // 计划采购数(需求量)
            content_02 += '<td>' + formatNullData(result[i].stockLevels) + '</td>';                                                // 库存数
            content_02 += '<td>' + result[i].demandedQuantity + '</td>';                                                           // 补给数
            content_02 += '<td style="border-right:none;">' + formatNullData(result[i].description) + '</td>';                     // 备注
            content_02 += '</tr>';

            $("#tabData21 tbody").append(content_01);
            $("#tabData22 tbody").append(content_02);
            content_01 = '';
            content_02 = '';
        }
        setTwoTableRowColor("tabData21", "tabData22");
        $(window).resize();               // 防止因为出现滚动条而造成画面显示问题
    }
    ScrollTo() {
        $('#divH22').scrollLeft($('#divD22').scrollLeft());
        $('#divD21').scrollTop($('#divD22').scrollTop());
    }
    SortTable(order_by) {
        this.orderby = order_by + ", P.StyleNo, L.UpdatedDate DESC";
        this.FetchLinesForPage(1);
    }
}

//-----------------------------------------------------------------------------
// 引入的补料单
//-----------------------------------------------------------------------------
class MyPageLinesMrpFeedingHeader extends BaseEditSlave {
    constructor() {
        super('', '', '');
    }
    // 构建明细数据列表
    BuildDataTable(result) {
        $('#tabMrpFeedingListData tbody').empty();
        if (result === null)
            return false;
        let content_01 = '';
        let sequence = 1;
        for (let i = 0; i < result.length; i++) {
            let linesid = result[i].linesId;
            sequence = i + 1;
            content_01 += '<tr _mash_id="' + linesid + '">';
            content_01 += '<td style="text-align:center;">' + sequence + '</td>';
            content_01 += '<td>' + formatNullData(result[i].billNo) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].feedingTypeName) + '</td>';
            content_01 += '</tr>';
            $('#tabMrpFeedingListData tbody').append(content_01);
            content_01 = '';
        }
        setOneTableRowColor("tabMrpFeedingListData");
    }
    ImportMrpFeeding() {
        let _this = this;
        showModal(1295, 630, '引入补料单', parent.basePath + '/tech/mrp_feeding_for_po/choice.html?isQuotedFlag=0&enterpriseId=' + $("#EnterpriseId").val(), null, ($dialog) => {
            let _exist = $.inArray($dialog, parent.arrDialog);
            if (_exist >= 0) {
                parent.arrDialog.splice($.inArray($dialog, parent.arrDialog), 1);
            }
            // 做选择设置
            if (parent.choice_success) {
                let MrpFeedingHeaderKeyList = [];
                let MrpFeedingLinesKeyList = [];
                for (let key in parent.arrChoice[0].SelectedHeaderList) {
                    MrpFeedingHeaderKeyList.push(parseInt(key));
                }
                for (let key in parent.arrChoice[0].SelectedLinesList) {
                    MrpFeedingLinesKeyList.push(key);
                }

                // 根据所选择的调达表，形成采购合同明细
                let _params = {};
                _params['HeaderId'] = parseInt($('#HeaderId').val());
                _params['CreatedBy'] = parseInt($("#UserId").val());
                _params['UpdatedBy'] = parseInt($("#UserId").val());
                _params['MrpFeedingHeaderId'] = MrpFeedingHeaderKeyList;
                _params['MrpFeedingLinesId'] = MrpFeedingLinesKeyList;
                _params['SeparateFlagByPartOfNeed'] = parseInt(parent.arrChoice[0].SeparateFlagByPartOfNeed);
                _params['Limit02'] = parseInt($("#page-size_02").val());
                _params['Limit03'] = parseInt($("#page-size_03").val());
                _params['Limit04'] = parseInt($("#page-size_04").val());
                _params['PoNo'] = $("#PoNo").val();

                $.ajax({
                    type: "POST",
                    url: parent.basePath + "/purchase/po/lines/mrp/feeding/insert.html",
                    timeout: 60 * 1000,
                    data: JSON.stringify(_params),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    beforeSend: function () {
                    }
                }).done((data) => {
                    // 刷新明细记录  
                    _this.BuildDataTable(data.LinesMrpFeedingList);
                    // 引入的补料单明细列表           
                    _InstancePageLinesMrpFeedingLines.BuildDataTable(data.LinesMrpFeedingLinesList);
                    // 设置订单的材料列表
                    _InstancePageLines.SetPoMaterialList(data.PoMaterialList);
                    // 合同明细表             
                    _InstancePageLines.BuildDataTable(data.PoLinesList);

                    ShowSuccessMessagePanel("引入补料单成功。");
                }).fail((data) => {
                    ajaxError(data, 1);
                }).always(( ) => {
                });
            }
            // 清空数组
            parent.arrChoice.splice(0, parent.arrChoice.length);
            parent.choice_success = false;
        });
    }
}

//-----------------------------------------------------------------------------
// 引入的补料单明细
//-----------------------------------------------------------------------------
class MyPageLinesMrpFeedingLines extends BaseEditSlave {
    constructor() {
        super('', '', '');
        this.orderby = "";
    }
    SetPageSize03() {
        $.cookie("po_list_mrp_feeding_pagesize", $("#page-size_03").val());
        this.FetchLinesForPage(1);
    }
    // 获取明细表分页信息
    GetFilterValue(pageIndex) {
        if (pageIndex !== 0) {
            $("abbr.page_indicator_block,#wrapper__navbar_03").attr("_msh_page", pageIndex);
        }

        let item = {};
        item['HeaderId'] = parseInt($.trim($("#HeaderId").val()));
        item['CurrentUserId'] = parseInt($("#UserId").val());      // 当前操作者，用于过滤供应商分组
        item['Limit'] = parseInt($("#page-size_03").val());        // limit;
        item['PageIndex'] = parseInt($("abbr.page_indicator_block,#wrapper__navbar_03").attr("_msh_page"));
        item['OrderBy'] = this.orderby;

        return JSON.stringify(item);
    }
    FetchLinesForPageNoFilter() {
        $("#StyleNoFilterValue_03").val("");
        $("#MaterialNoFilterValue_03").val("");
        $("#MaterialNameFilterValue_03").val("");
        $("#MaterialColourNameFilterValue_03").val("");

        $("abbr.page_indicator_block,#wrapper__navbar_03").attr("_msh_page", 1);
        this.FetchLinesForPage(1);
    }
    // 取得引入的补料单明细分页信息
    FetchLinesForPage(pageIndex) {
        $.ajax({
            type: "POST",
            url: parent.basePath + "/purchase/po/lines/mrp/feeding/fetchForPage.html",
            timeout: 60 * 1000,
            data: this.GetFilterValue(pageIndex),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
                $("#loading__indicator_03 i").addClass("fa-spin");
                $("#loading__indicator_03").show();
            }
        }).done((data) => {
            this.BuildDataTable(data);
        }).fail((data) => {
            ajaxError(data, 1);
        }).always(() => {
            $("#loading__indicator_03 i").removeClass("fa-spin");
            $("#loading__indicator_03").hide();
        });
    }
    // 构建明细数据列表
    BuildDataTable(result) {
        $('#tabData31 tbody').empty();
        $('#tabData32 tbody').empty();

        if (result.Success === false) {
            return;
        }

        // 设置翻页控件
        if (result.TotalPages > 0) {  //总页数
            $("#wrapper__navbar_03").data("swPagination").options.max_page = result.TotalPages;
        } else {
            $("#wrapper__navbar_03").data("swPagination").options.max_page = 1;
        }
        if (result.PageIndex > 0) { //当前页数
            $("#wrapper__navbar_03").data("swPagination").options.current_page = result.PageIndex;
            $("#wrapper__navbar_03").data("swPagination").setPage(result.PageIndex);
        } else {
            $("#wrapper__navbar_03").data("swPagination").options.current_page = 1; //当前页数
            $("#wrapper__navbar_03").data("swPagination").setPage(1);
        }

        // 得到数据列表
        result = result.DataList;
        if (result === null) {
            return false;
        }

        let content_01 = '';
        let content_02 = '';
        for (let i = 0; i < result.length; i++) {
            let id = result[i].linesId;
            content_01 += '<tr _mash_id="' + id + '">';
            content_01 += '<td>' + formatNullData(result[i].billNo) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].styleNo) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].materialName) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].materialCode) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].supplierName) + '</td>';
            content_01 += '<td></td>';
            content_01 += '</tr>';

            content_02 += '<tr>';
            content_02 += '<td>' + formatNullData(result[i].materialColourNumber) + '</td>';
            content_02 += '<td>' + formatNullData(result[i].materialColourName) + '</td>';
            content_02 += '<td style="text-align:center;" _msh_uomid="' + result[i].uomId + '">' + formatNullData(result[i].uomName) + '</td>';
            content_02 += '<td>' + formatNullData(result[i].demandedQuantity) + '</td>';
            content_02 += '<td>' + formatNullData(result[i].specification) + '</td>';
            content_02 += '<td>' + formatNullData(result[i].destination) + '</td>';
            content_02 += '<td style="border-right:none;">' + formatNullData(result[i].description) + '</td>';    //备注            
            content_02 += '</tr>';

            $("#tabData31 tbody").append(content_01);
            $("#tabData32 tbody").append(content_02);
            content_01 = '';
            content_02 = '';
        }
        setTwoTableRowColor("tabData31", "tabData32");
        $(window).resize();               // 防止因为出现滚动条而造成画面显示问题
    }
    ScrollTo() {
        $('#divH32').scrollLeft($('#divD32').scrollLeft());
        $('#divD31').scrollTop($('#divD32').scrollTop());
    }
    SortTable(order_by) {
        this.orderby = order_by;
        this.FetchLinesForPage(1);
    }
}

//-----------------------------------------------------------------------------
// 订单明细
//-----------------------------------------------------------------------------
class MyPageLines extends BaseEditSlave {
    constructor() {
        super('', '', '');
        this.selectedItemList = [];
        this.orderby = "";
        this.$input = null;
    }
    SetPageSize04() {
        $.cookie("po_lines_list_pagesize", $("#page-size_04").val());
        this.FetchLinesForPage(1);
    }
    // 获取明细表分页信息
    GetFilterValue(pageIndex) {
        if (pageIndex !== 0) {
            $("abbr.page_indicator_block,#wrapper__navbar_04").attr("_msh_page", pageIndex);
        }

        let item = {};
        item['HeaderId'] = parseInt($.trim($("#HeaderId").val()));
        item['CurrentUserId'] = parseInt($("#UserId").val());     // 当前操作者，用于过滤供应商分组
        item['Limit'] = parseInt($("#page-size_04").val());       // limit;
        item['PageIndex'] = parseInt($("abbr.page_indicator_block,#wrapper__navbar_04").attr("_msh_page"));

        item['StyleNoFilterVal'] = formatNullInputValue($.trim($("#StyleNoFilterValue_04").val()));
        item['MaterialNoFilterVal'] = formatNullInputValue($.trim($("#MaterialNoFilterValue_04").val()));
        item['MaterialNameFilterVal'] = formatNullInputValue($.trim($("#MaterialNameFilterValue_04").val()));
        if ($("#PoMaterialList").val() !== "-1") {
            item['MaterialNameFilterVal'] = $("#PoMaterialList").val();
        }
        item['MaterialColourNameFilterVal'] = formatNullInputValue($.trim($("#MaterialColourNameFilterValue_04").val()));
        //item['SpecificationFilterVal'] = $("#SpecificationFilterValue_04").val();

        item['OrderBy'] = this.orderby;
        return JSON.stringify(item);
    }
    FetchLinesForPageNoFilter() {
        $("#StyleNoFilterValue_04").val("");
        $("#MaterialNoFilterValue_04").val("");
        $("#MaterialNameFilterValue_04").val("");
        $("#MaterialColourNameFilterValue_04").val("");

        $("abbr.page_indicator_block,#wrapper__navbar_04").attr("_msh_page", 1);
        this.FetchLinesForPage(1);
    }
    // 取得引入的订单明细分页信息
    FetchLinesForPage(pageIndex) {
        let _this = this;
        $.ajax({
            type: "POST",
            url: parent.basePath + "/purchase/po/lines/fetchForPage.html",
            timeout: 60 * 1000,
            data: _this.GetFilterValue(pageIndex),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
                $("#loading__indicator_04 i").addClass("fa-spin");
                $("#loading__indicator_04").show();
            }
        }).done((data) => {
            if (data.Success === true) {
                _this.BuildDataTable(data);
            }
        }).fail((data) => {
            ajaxError(data, 1);
        }).always(() => {
            $("#loading__indicator_04 i").removeClass("fa-spin");
            $("#loading__indicator_04").hide();
        });
    }
    // 构建明细数据列表
    BuildDataTable(result) {
        let isPreparedBy = false;
        if (parseInt($("#UserId").val()) !== parseInt($("#PurchasedBy").val())) {
            if ($("#RoleName").val().indexOf("系统管理员") === -1) {
                isPreparedBy = false;
            } else {
                isPreparedBy = true;
            }
        } else {
            isPreparedBy = true;
        }


        $("#CheckAll_04").prop("checked", false);
        let current_page = result.PageIndex;
        // 设置翻页控件
        if (result.TotalPages > 0) {  //总页数
            $("#wrapper__navbar_04").data("swPagination").options.max_page = result.TotalPages;
        } else {
            $("#wrapper__navbar_04").data("swPagination").options.max_page = 1;
        }
        if (result.PageIndex > 0) { //当前页数
            $("#wrapper__navbar_04").data("swPagination").options.current_page = result.PageIndex;
            $("#wrapper__navbar_04").data("swPagination").setPage(result.PageIndex);
        } else {
            $("#wrapper__navbar_04").data("swPagination").options.current_page = 1; //当前页数
            $("#wrapper__navbar_04").data("swPagination").setPage(1);
        }

        // 得到数据列表
        $('#tabData41 tbody').empty();
        $('#tabData42 tbody').empty();
        result = result.DataList;
        if (result === undefined || result === null) {
            this.numCheckbox = 0;
            return false;
        }

        this.numCheckbox = result.length;
        let content_01 = '';
        let content_02 = '';
        for (let i = 0; i < result.length; i++) {
            let id = result[i].linesId;
            let sequence = i + 1 + (current_page - 1) * parseInt($("#page-size_04").val());
            content_01 += '<tr _mash_id="' + id + '" _supplierId="' + result[i].supplierId + '" _rowFlag="' + result[i].rowFlag + '">';
            if (parseInt(result[i].rowFlag) === 0) {
                if ($("#CheckedByName").val() !== "" || $("#ActionAcl_4").length === 0 || parseInt($("#ActionAcl_4").val() === 0) || (parseInt($("#UserId").val()) !== parseInt($("#PurchasedBy").val()))) {
                    content_01 += '<td></td>';
                } else {
                    content_01 += '<td style="padding-left:6px;"><label class="btn" for="R-' + result[i].linesId + '"><input id="R-' + result[i].linesId + '" name="_check_row" type="checkbox" onclick="_InstancePageLines.DoCheckRow($(this),\'_check_row\', $(\'#CheckAll_04\'))"; value="' + result[i].linesId + '"/><i></i><span></span></label></td>';
                }
                content_01 += '<td style="text-align:center;">' + sequence + '</td>';
                if ($("#ActionAcl_4").length === 0 || parseInt($("#ActionAcl_4").val() === 0)) {  // 无删除权限
                    content_01 += '<td></td>';
                } else {
                    // 如果有审核或不是作成者，也不能删除
                    if ($("#CheckedByName").val() !== "" || (parseInt($("#UserId").val()) !== parseInt($("#PurchasedBy").val()))) {
                        content_01 += '<td></td>';
                    } else {
                        content_01 += '<td class="column__action"><span title="删除" class="trash act__delete" onclick="_InstancePageLines.DoDelete($(this));"><i class="fa-all fa-trash-o fa-1"></i></span></td>';
                    }
                }
                content_01 += '<td>' + formatNullData(result[i].styleNo) + '</td>';
                if (parseInt(result[i].supplierId) === parseInt($("#SupplierId").val())) {
                    content_01 += '<td _mash_old_partno="' + formatNullData(result[i].materialCode) + '" _mash_materialId="' + result[i].materialId + '" title="供应商：' + formatNullData(result[i].supplierName) + '"supplierName>' + formatNullData(result[i].materialCode) + '</td>';
                    content_01 += '<td>' + formatNullData(result[i].materialName) + '</td>';
                } else {
                    content_01 += '<td class="error" _mash_old_partno="' + formatNullData(result[i].materialCode) + '" _mash_materialId="' + result[i].materialId + '" title="供应商：' + formatNullData(result[i].supplierName) + '"supplierName>' + formatNullData(result[i].materialCode) + '</td>';
                    content_01 += '<td class="error">' + formatNullData(result[i].materialName) + '</td>';
                }
            }
            // 附加费
            if (parseInt(result[i].rowFlag) === 2) {
                content_01 += '<td></td>';
                content_01 += '<td style="text-align:center;">' + sequence + '</td>';
                content_01 += '<td colspan="4" style="text-align:center;">附加费（' + result[i].description + '）</td>';
            }
            content_01 += '</tr>';

            content_02 += '<tr _mash_id="' + id + '">';
            if (parseInt(result[i].rowFlag) === 0) {
                content_02 += '<td class="edited-cell">' + formatNullData(result[i].materialColourNumber) + '</td>';     // 材料色码
                content_02 += '<td>' + formatNullData(result[i].materialColourName) + '</td>';                  // 材料色
                content_02 += '<td class="edited-cell">' + formatNullData(result[i].specification) + '</td>';   // 规格
                content_02 += '<td class="edited-cell" style="text-align:center;" _mash_uomid="' + result[i].uomId + '" _mash_mrp_uomid="' + formatNullData(result[i].mdpUomId) + '" _Coefficient="' + formatNullData(result[i].coefficient) + '">' + formatNullData(result[i].uomName) + '</td>';     // _IsCoefficient："0"-不用米转系数，“1”-需要使用系数进行转换。计量单位
                content_02 += '<td>' + formatNullData(result[i].planQuantity) + '</td>';     // 计划数量
                // 损耗
                //if (result[i].lossId === null) {
                //   content_02 += '<td class="error" title="该材料没有设置订货损耗">&nbsp;</td>';
                //} else {
                content_02 += '<td class="edited-cell">' + formatNullData(result[i].sparedQuantity === 0 ? null : result[i].sparedQuantity) + '</td>';
                //}
                content_02 += '<td class="edited-cell" _mash_plan_quantity="' + result[i].planQuantity + '">' + formatNullData(result[i].poQuantity === 0 ? null : result[i].poQuantity) + '</td>';  // 采购数量
                content_02 += '<td class="edited-cell">' + formatNullData(result[i].arrivalAllowed) + '</td>';                              // 到货允许
                content_02 += '<td>' + formatNullData(result[i].maxArrivalQuantity === 0 ? null : result[i].maxArrivalQuantity) + '</td>';  // 最大到货数
                if (isPreparedBy === true) {
                    content_02 += '<td>' + formatNullData(result[i].unitPrice === null ? null : result[i].unitPrice) + '</td>';    // 基础单价
                    content_02 += '<td class="edited-cell">' + formatNullData(result[i].poUnitPrice === null ? null : result[i].poUnitPrice) + '</td>';  // 订货单价
                    if (result[i].poUnitPrice > result[i].unitPrice)
                        content_02 += '<td style="text-align:center;">' + '<span class="n2">异常&nbsp;↑</span>' + '</td>';    // 价格异常(高于标准)
                    if (result[i].poUnitPrice < result[i].unitPrice)
                        content_02 += '<td style="text-align:center;">' + '<span class="n1">异常&nbsp;↓</span>' + '</td>';    // 价格异常(低于标准)
                    if (result[i].poUnitPrice === result[i].unitPrice)
                        content_02 += '<td style="text-align:center;">&nbsp;</td>';                                          // 价格正常
                    content_02 += '<td>' + (result[i].poQuantity * result[i].poUnitPrice).toFixed(2) + '</td>';              // 金额
                } else {
                    content_02 += '<td></td>';    // 基础单价
                    content_02 += '<td></td>';    // 订货单价
                    content_02 += '<td style="text-align:center;">-</td>';    // 价格异常
                    content_02 += '<td></td>';              // 金额
                }
                let _stockInQuantity = result[i].stockInQuantity === null ? null : result[i].stockInQuantity;
                if (_stockInQuantity === null || _stockInQuantity < result[i].poQuantity) {
                    content_02 += '<td style="background:red;color:#fff;">' + formatNullData(result[i].stockInQuantity === null ? null : result[i].stockInQuantity) + '</td>';  // 到货数
                } else {
                    content_02 += '<td>' + formatNullData(result[i].stockInQuantity === null ? null : result[i].stockInQuantity) + '</td>';  // 到货数
                }
                content_02 += '<td class="edited-cell">' + formatNullData(result[i].description) + '</td>';              // 备注
                //content_02 += '<td style="border-right:none;">' + formatNullData(result[i].destination) + '</td>';       // 发货目的地
            }
            // 这是附加费行
            if (parseInt(result[i].rowFlag) === 2) {
                content_02 += '<td colspan="6"></td>';
                content_02 += '<td _mash_plan_quantity="' + result[i].planQuantity + '">' + formatNullData(result[i].poQuantity === 0 ? null : result[i].poQuantity) + '</td>'; // 采购数量
                content_02 += '<td colspan="3"></td>';
                content_02 += '<td>' + formatNullData(result[i].poUnitPrice === null ? null : result[i].poUnitPrice) + '</td>';   // 订货单价
                content_02 += '<td style="text-align:center;">&nbsp;</td>';                                           // 价格正常
                content_02 += '<td>' + (result[i].poQuantity * result[i].poUnitPrice).toFixed(2) + '</td>';           // 金额
                content_02 += '<td>' + formatNullData(result[i].stockInQuantity === null ? null : result[i].stockInQuantity) + '</td>';  // 到货数
                content_02 += '<td>' + formatNullData(result[i].description) + '</td>';                               // 备注
                //content_02 += '<td style="border-right:none;">' + formatNullData(result[i].destination) + '</td>';    // 发货目的地
            }
            content_02 += '</tr>';

            $("#tabData41 tbody").append(content_01);
            $("#tabData42 tbody").append(content_02);
            content_01 = '';
            content_02 = '';
        }

        let cell_id = "_cell__field";
        let cell_name = "__cell__field";
        let _this = this;
        $('#tabData42 tbody tr').find("td.edited-cell").click(function () {
            switch ($(this).index()) {
                case 3:
                    OnCellPopupEditEvent($(this), cell_id, cell_name, ($input) => {
                        _this.DoChoiceUom($input);
                    });
                    break;
                case 5:  // 订货损耗
                    OnCellClickEvent($(this), cell_id, cell_name, 0, ($input) => {
                        _this.SetSparedQuantity($(this));
                    });
                    break;
                case 6:  // 订货数量
                    OnCellClickEvent($(this), cell_id, cell_name, 0, ($input) => {
                        _this.SetPoQuntity($(this));
                    });
                    break;
                case 7:  // 到货允许
                    OnCellClickEvent($(this), cell_id, cell_name, 0, ($input) => {
                        _this.SetArrivalAllowed($(this));
                    });
                    break;
                case 10:  // 订货单价
                    OnCellClickEvent($(this), cell_id, cell_name, 0, ($input) => {
                        _this.SetOrderAmount($(this));
                    });
                    break;
                default:
                    OnCellClickEvent($(this), cell_id, cell_name, 0);
                    break;
            }
        });
        setTwoTableRowColor("tabData41", "tabData42");
        $(window).resize();               // 防止因为出现滚动条而造成画面显示问题
        this.ResetSelectRowStatus();

        $("#tabData42").keyup(function (e) {
            if (e.keyCode === 13) {
                //ClearGridMaterialNoError();
                //$("#ButSaveLines").focus();
                //this.SaveLines();
            }
        });
    }
    // 设置订单材料下拉列表
    SetPoMaterialList(data) {
        $("#PoMaterialList").empty();
        if (data !== null) {
            let options = [];
            options.push('<option value="-1">-- 按材料过滤 --</option>');
            for (let i = 0; i < data.length; i++) {
                options.push('<option value="', data[i].materialName, '">', data[i].materialName, '</option>');
            }
            $("#PoMaterialList").html(options.join(''));
        } else {
            let options = [];
            options.push('<option value="-1">-- 按材料过滤 --</option>');
            $("#PoMaterialList").html(options.join(''));
        }
    }
    // 编辑附加费
    DoEditSurCharges() {
        showModal(1095, 538, '编辑附加费', parent.basePath + '/purchase/po/lines/surcharges/edit.html', null, ($dialog) => {
            let _exist = $.inArray($dialog, parent.arrDialog);
            if (_exist >= 0) {
                parent.arrDialog.splice($.inArray($dialog, parent.arrDialog), 1);
            }
        });
        $(window).resize();
    }
    // 得到订单明细数据
    GetLinesData() {
        let params = {};
        params['HeaderId'] = parseInt($("#HeaderId").val());
        params['UpdatedBy'] = parseInt($("#UserId").val());
        params['CurrentUserId'] = parseInt($("#UserId").val());      // 当前操作者，用于过滤供应商分组
        params['Limit'] = parseInt($("#page-size_04").val());
        params['PageIndex'] = parseInt($("abbr.page_indicator_block,#wrapper__navbar_04").attr("_msh_page"));
        params['OrderBy'] = this.orderby;
        let _result = [];
        $('#tabData42 tbody').find("tr").each(function (index) {
            let $row01 = $('#tabData41 tbody').find('tr').eq(index);
            if ($(this).find('td.dirty').length > 0 || $row01.find('td.dirty').length > 0) {
                let item = {};
                item['headerId'] = $('#HeaderId').val();
                item['linesId'] = $(this).attr('_mash_id');
                item['styleNo'] = $.trim($row01.find('td').eq(3).text());                                        // 款号
                item['materialId'] = $.trim($row01.find('td').eq(4).attr("_mash_materialId"));                   // 材料标识
                item['materialCode'] = $.trim($row01.find('td').eq(4).text());                                   // 新材料号
                item['materialColourNumber'] = formatNullInputValue($.trim($(this).find('td').eq(0).text()));    // 材料色码
                item['materialColourName'] = formatNullInputValue($.trim($(this).find('td').eq(1).text()));      // 材料色名
                item['specification'] = formatNullInputValue($.trim($(this).find('td').eq(2).text()));           // 规格
                item['uomId'] = formatNullInputValue($.trim($(this).find('td').eq(3).attr("_mash_uomid")));      // 计量单位
                // 订货损耗
                item['sparedQuantity'] = formatNullInputValue($.trim($(this).find('td').eq(5).text()));
                // 采购数量
                if ($(this).find('td').eq(6).hasClass("dirty")) {
                    let _poQuantity = formatNullInputValue($.trim($(this).find('td').eq(6).text())) === null ? 0 : $.trim($(this).find('td').eq(6).text());      // 订购数，初始采购数量=计划数量
                    item['poQuantity'] = _poQuantity;
                } else {
                    let _plan = parseFloat($.trim($(this).find('td').eq(4).text()));
                    let _loss = $.trim($(this).find('td').eq(5).text()) === "" ? 0 : parseFloat($.trim($(this).find('td').eq(5).text()));
                    if ($(this).find('td').eq(5).hasClass("dirty")) {
                        if (_loss >= 1) {
                            item['poQuantity'] = Math.ceil((_plan + _loss).toFixed(1));
                        } else {
                            item['poQuantity'] = Math.ceil(_plan + _plan * _loss);
                        }
                    } else {
                        item['poQuantity'] = formatNullInputValue($.trim($(this).find('td').eq(6).text()));
                    }
                    $(this).find('td').eq(6).text(item['poQuantity']);
                }
                // 到货允许
                item['arrivalAllowed'] = ($.trim($(this).find('td').eq(7).text())) === '' ? null : $.trim($(this).find('td').eq(7).text());
                let _allowed = $.trim($(this).find('td').eq(7).text()) === "" ? 0 : parseFloat($.trim($(this).find('td').eq(7).text()));
                let _poQuntity = parseFloat($(this).find('td').eq(6).text());
                if (_allowed >= 1) {
                    $(this).find('td').eq(8).text(Math.ceil((_poQuntity + _allowed).toFixed(1)));
                } else {
                    $(this).find('td').eq(8).text(Math.ceil(_poQuntity + _poQuntity * _allowed));
                }
                item['maxArrivalQuantity'] = formatNullInputValue($.trim($(this).find('td').eq(8).text()));
                item['poUnitPrice'] = formatNullInputValue($.trim($(this).find('td').eq(10).text())) === null ? 0 : $.trim($(this).find('td').eq(10).text());  // 采购单价

                // 设置采购金额
                let _unitprice = $.trim($(this).find('td').eq(10).text()) === "" ? 0 : parseFloat($.trim($(this).find('td').eq(10).text()));
                $(this).find('td').eq(12).text((_poQuntity * _unitprice).toFixed(2));

                item['description'] = formatNullInputValue($.trim($(this).find('td').eq(14).text()));            // 备注
                item['createdBy'] = $("#UserId").val();
                item['updatedBy'] = $("#UserId").val();

                _result.push(item);
            }
        });
        params['UpdatedLinesList'] = _result;

        return params;
        //return JSON.stringify(_result);
    }
    DoSaveLines() {
        super.DoAjax(this.GetLinesData(), "/purchase/po/lines/update.html", (data, _this) => {
            if (data.Success) {
                // 设置订单的材料列表
                _this.SetPoMaterialList(data.PoMaterialList);
                // 合同明细表             
                _this.BuildDataTable(data.PoLinesList);
                //$('#tabData41 tbody').find('td.dirty').removeClass("dirty");
                //$('#tabData42 tbody').find('td.dirty').removeClass("dirty");
                $("#CheckAll").prop("checked", false);

                ShowSuccessMessagePanel("订单明细更新完成。");
            } else {
                ShowErrorMessagePanel("没有要更新的数据。");
            }
        });
    }
    // 批量清空损耗
    DoBatchCleanLoss() {
        if ($('#tabData41 tbody').find("tr.row__selected").length === 0) {
            ShowErrorMessagePanel("请先选择要清空的数据。");
            return false;
        }
        let _this = this;
        showModal(390, 140, '确认删除', '', null, null, 1, '请问，确定要清空所选数据的订货损耗吗？', function () {
            $.ajax({
                type: "POST",
                url: parent.basePath + "/purchase/po/lines/batchCleanLoss.html",
                timeout: 30 * 1000,
                data: _this.GetCheckedLinesData(),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                beforeSend: function () {
                }
            }).done(function (data) {
                // 合同明细表           
                _this.BuildDataTable(data.PoLinesList);
                // 设置订单的材料列表
                _this.SetPoMaterialList(data.PoMaterialList);
                $("#CheckAll_04").prop("checked", false);

                ShowSuccessMessagePanel("订货损耗清除成功。");
            }).fail(function (data) {
                ajaxError(data, 1);
            }).always(function ( ) {
            });
        });
    }
    // 删除
    DoDelete($self) {
        let params = {};
        params['HeaderId'] = parseInt($("#HeaderId").val());
        params['LinesId'] = $self.parent().parent().attr("_mash_id");
        params['DeletedBy'] = parseInt($("#UserId").val());
        params['CurrentUserId'] = parseInt($("#UserId").val());      // 当前操作者，用于过滤供应商分组
        params['Limit02'] = parseInt($("#page-size_02").val());
        params['Limit03'] = parseInt($("#page-size_03").val());
        params['Limit04'] = parseInt($("#page-size_04").val());
        params['PageIndex04'] = parseInt($("abbr.page_indicator_block,#wrapper__navbar_04").attr("_msh_page"));
        params['OrderBy'] = this.orderby;

        super.DeleteLines(params, "/purchase/po/lines/delete.html", function (data, _this) {
            // 合同明细表           
            _this.BuildDataTable(data.PoLinesList);
            // 设置订单的材料列表
            _this.SetPoMaterialList(data.PoMaterialList);
            $("#CheckAll_04").prop("checked", false);
            // 引入的调达表明细列表
            _InstancePageLinesMrpHeader.BuildDataTable(data.LinesMrpList);
            _InstancePageLinesMrpLines.BuildDataTable(data.LinesMrpLinesList);
            // 引入的补料单明细列表
            _InstancePageLinesMrpFeedingHeader.BuildDataTable(data.LinesMrpFeedingList);
            _InstancePageLinesMrpFeedingLines.BuildDataTable(data.LinesMrpFeedingLinesList);

            ShowSuccessMessagePanel("删除成功。");
        });
    }
    // 批量删除
    DoBatchDeleteLines() {
        if ($("input[type='checkbox'][name='_check_row']:checked").length <= 0) {
            ShowErrorMessagePanel("请选择要删除的数据。");
            return false;
        }

        let params = {};
        params['HeaderId'] = parseInt($("#HeaderId").val());
        params['DeletedBy'] = parseInt($("#UserId").val());
        params['CurrentUserId'] = parseInt($("#UserId").val());      // 当前操作者，用于过滤供应商分组
        params['Limit02'] = parseInt($("#page-size_02").val());
        params['Limit03'] = parseInt($("#page-size_03").val());
        params['Limit04'] = parseInt($("#page-size_04").val());
        params['PageIndex04'] = parseInt($("abbr.page_indicator_block,#wrapper__navbar_04").attr("_msh_page"));
        params['OrderBy'] = this.orderby;

        let choiced_data = [];
        if ($("input[type='checkbox'][name='_check_row']:checked").length > 0) {
            $("input[type='checkbox'][name='_check_row']:checked").each(function () {
                let item = {};
                item['headerId'] = $("#HeaderId").val();
                item['linesId'] = $(this).parent().parent().parent().attr("_mash_id");
                item['deletedBy'] = $.trim($("#UserId").val());
                choiced_data.push(item);
            });
        }
        params['DeletedLinesList'] = choiced_data;

        super.DoAjax(params, "/purchase/po/lines/batch_delete.html", (data, _this) => {
            // 刷新明细记录  
            _InstancePageLinesMrpHeader.BuildDataTable(data.LinesMrpList);
            // 引入的补料单明细列表           
            _InstancePageLinesMrpLines.BuildDataTable(data.LinesMrpLinesList);
            _InstancePageLinesMrpFeedingHeader.BuildDataTable(data.LinesMrpFeedingList);
            // 引入的补料单明细列表           
            _InstancePageLinesMrpFeedingLines.BuildDataTable(data.LinesMrpFeedingLinesList);
            // 设置订单的材料列表
            _this.SetPoMaterialList(data.PoMaterialList);
            // 合同明细表             
            _this.BuildDataTable(data.PoLinesList);

            $("#CheckAll").prop("checked", false);
            ShowSuccessMessagePanel("批量删除完成。");
        });
    }
    // 更改当前行材料
    DoUpdateRowMaterial() {
        if ($("input[type='checkbox'][name='_check_row']:checked").length <= 0) {
            ShowErrorMessagePanel("请选择要更改的数据。");
            return false;
        }

        let _choice = new CommonChoice();
        let _row = $("input[type='checkbox'][name='_check_row']:checked:first").parent().parent().parent();   // 得到选择的第一行
        let _params = '0&materialName=' + _row.find("td").eq(5).text() + '&supplierName=' + $("#SupplierName").val();
        _choice.DoChoiceMaterial(_params, '选择材料', (data) => {
            if (data) {
                let _materialId = data[0];    // 料ID

                let params = {};
                params['HeaderId'] = parseInt($("#HeaderId").val());
                params['UpdatedBy'] = parseInt($("#UserId").val());
                params['CurrentUserId'] = parseInt($("#UserId").val());      // 当前操作者，用于过滤供应商分组
                params['Limit02'] = parseInt($("#page-size_02").val());
                params['Limit03'] = parseInt($("#page-size_03").val());
                params['Limit04'] = parseInt($("#page-size_04").val());
                params['PageIndex04'] = parseInt($("abbr.page_indicator_block,#wrapper__navbar_04").attr("_msh_page"));
                params['OrderBy'] = this.orderby;

                let updatedItemList = [];
                if ($("input[type='checkbox'][name='_check_row']:checked").length > 0) {
                    $("input[type='checkbox'][name='_check_row']:checked").each(function () {
                        let item = {};
                        item['headerId'] = $("#HeaderId").val();
                        item['linesId'] = $(this).parent().parent().parent().attr("_mash_id");
                        item['materialId'] = _materialId;
                        updatedItemList.push(item);
                    });
                }
                params['UpdatedLinesList'] = updatedItemList;

                showModal(350, 140, '确认删除', '', null, null, 1, '请问，确定要改变当前材料吗？', () => {
                    this.OnDoUpdateRowMaterial(params);
                });
            }
        });
    }
    OnDoUpdateRowMaterial(params) {
        super.DoAjax(params, "/purchase/po/lines/updateRowMaterial.html", (data, $self) => {
            if (data.Success) {
                // 刷新明细记录  
                _InstancePageLinesMrpHeader.BuildDataTable(data.LinesMrpList);
                // 引入的补料单明细列表           
                _InstancePageLinesMrpLines.BuildDataTable(data.LinesMrpLinesList);
                _InstancePageLinesMrpFeedingHeader.BuildDataTable(data.LinesMrpFeedingList);
                // 引入的补料单明细列表           
                _InstancePageLinesMrpFeedingLines.BuildDataTable(data.LinesMrpFeedingLinesList);
                // 设置订单的材料列表
                $self.SetPoMaterialList(data.PoMaterialList);
                // 合同明细表             
                $self.BuildDataTable(data.PoLinesList);

                $("#CheckAll").prop("checked", false);
                ShowSuccessMessagePanel("材料改变成功。");
            } else {
                ShowErrorMessagePanel("没有数据被更改。");
            }
        });
    }
    SetRowStatus($self) {
        let key = $self.val();
        let $row = $self.parent().parent().parent();
        let rowIndex = $row.index();
        if ($self.is(":checked") === true) {
            $row.addClass("row__selected");
            $('#tabData42 tbody tr:eq(' + rowIndex + ')').addClass("row__selected");
            // 设置 编辑、删除按钮失效
            $row.children('td').eq(2).children('span').eq(0).attr("onclick", "");
            let item = {};
            // 为翻页选择做准备
            item["linesId"] = key;
            this.selectedItemList[key] = item;
        } else {
            $row.removeClass("row__selected");
            $('#tabData42 tbody tr:eq(' + rowIndex + ')').removeClass("row__selected");
            // 设置删除按钮有效
            var _event_delete_onclick = "_InstancePageLines.DoDelete($(this))";
            $row.children('td').eq(2).children('span').eq(0).attr("onclick", _event_delete_onclick);
            delete this.selectedItemList[key];
        }
    }
    // 每次翻页都恢复选定结果
    ResetSelectRowStatus() {
        let _this = this;
        $("#tabData41 tbody").find("tr").each(function (index) {
            let key = $(this).attr("_mash_id");
            if (_this.selectedItemList[key] !== undefined) {
                $(this).children("td").eq(0).children("label").eq(0).children("input[type='checkbox'][name='_check_row']").eq(0).prop('checked', true);
                $(this).addClass("row__selected");
                $('#tabData42 tbody tr:eq(' + index + ')').addClass("row__selected");
            }
        });
        // 设置选择全部的状态
        let n = $("input[type='checkbox'][name='_check_row']:checked").length;
        if (n < $("#tabData41 tbody").find("tr").length || n === 0) {
            $("#CheckAll_04").prop("checked", false);
        } else {
            $("#CheckAll_04").prop("checked", true);
        }
    }
    // 批量选择的数据
    GetCheckedLinesData() {
        let _result = [];
        if ($("input[type='checkbox'][name='_check_row']:checked").length > 0) {
            $("input[type='checkbox'][name='_check_row']:checked").each(function () {
                let $tr = $(this).parent().parent().parent();
                let item = {};
                item['headerId'] = parseInt($("#HeaderId").val());
                item['linesId'] = $(this).val();
                item['materialCode'] = $.trim($tr.find("td").eq(8).text());
                item['deletedBy'] = $("#UserId").val();
                _result.push(item);
            });
        }
        return JSON.stringify(_result);
    }
    // 设置订货允差
    SetSparedQuantity($td) {
        let _plan = parseFloat($td.parent().find('td').eq(4).text());
        let _loss = $.trim($td.children("input").val()) === "" ? 0 : parseFloat($.trim($td.children("input").val()));
        let _new = 0;
        if (_loss >= 1) {
            _new = Math.ceil((_plan + _loss).toFixed(1));
            $td.parent().find('td').eq(6).text(_new);
        } else {
            _new = Math.ceil(_plan + _plan * _loss);
            $td.parent().find('td').eq(6).text(_new);
        }
        // 设置到货允许
        let _poQuntity = _new;
        _loss = $.trim($td.parent().find('td').eq(7).text()) === "" ? 0 : parseFloat($.trim($td.parent().find('td').eq(7).text()));
        if (_loss >= 1) {
            _new = Math.ceil((_poQuntity + _loss).toFixed(1));
            $td.parent().find('td').eq(8).text(_new);
        } else {
            _new = Math.ceil(_poQuntity + _poQuntity * _loss);
            $td.parent().find('td').eq(8).text(_new);
        }
        // 设置采购金额
        let _unitprice = $.trim($td.parent().find('td').eq(10).text()) === "" ? 0 : parseFloat($.trim($td.parent().find('td').eq(10).text()));
        $td.parent().find('td').eq(12).text((_poQuntity * _unitprice).toFixed(2));
    }
    SetPoQuntity($td) {
        let _poQuntity = $.trim($td.children("input").val()) === "" ? 0 : parseFloat($.trim($td.children("input").val()));
        // 设置采购金额
        let _unitprice = $.trim($td.parent().find('td').eq(10).text()) === "" ? 0 : parseFloat($.trim($td.parent().find('td').eq(10).text()));
        $td.parent().find('td').eq(12).text((_poQuntity * _unitprice).toFixed(2));
    }
    // 设置到货允许
    SetArrivalAllowed($td) {
        let _poQuntity = parseFloat($td.parent().find('td').eq(6).text());
        let _loss = $.trim($td.children("input").val()) === "" ? 0 : parseFloat($.trim($td.children("input").val()));
        if (_loss >= 1) {
            let _new = Math.ceil((_poQuntity + _loss).toFixed(1));
            $td.parent().find('td').eq(8).text(_new);
        } else {
            let _new = Math.ceil(_poQuntity + _poQuntity * _loss);
            $td.parent().find('td').eq(8).text(_new);
        }
    }
    // 设置订货金额
    SetOrderAmount($td) {
        let _poQuntity = parseFloat($td.parent().find('td').eq(6).text());
        let _unitprice = $.trim($td.children("input").val()) === "" ? 0 : parseFloat($.trim($td.children("input").val()));
        $td.parent().find('td').eq(12).text((_poQuntity * _unitprice).toFixed(2));
    }
    DoChoiceUom($input) {
        this.$input = $input;
        let _choice = new CommonChoice();
        _choice.DoChoiceUom(0, "选择单位", (data) => {
            if (data === false) {
                this.$input.focus();
            } else {
                this.$input.parent().attr("_mash_uomid", parent.arrChoice[0][0]);
                this.$input.val(parent.arrChoice[0][1]);
                this.$input.focus();
            }
        });
    }
    ScrollTo() {
        $('#divH42').scrollLeft($('#divD42').scrollLeft());
        $('#divD41').scrollTop($('#divD42').scrollTop());
    }
    SortTable(order_by) {
        this.orderby = order_by;
        this.FetchLinesForPage(1);
    }
}

var _InstancePageHeader = null;
var _InstancePageLines = null;
var _InstancePageLinesMrpHeader = null;
var _InstancePageLinesMrpLines = null;
var _InstancePageLinesMrpFeedingHeader = null;
var _InstancePageLinesMrpFeedingLines = null;

//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    let _pageStatus = parseInt($("#Action").val());
    let _dataId = $("#HeaderId").val();

    let po_list_result = $.cookie("po_list_result") === undefined ? "" : $.cookie("po_list_result");
    let _pageListData = [];
    if (po_list_result !== "") {
        _pageListData = po_list_result.split(',');
        $("#rec_total_rows").text(_pageListData.length);
        $("#rec_cur_row").text($.inArray(_dataId, _pageListData) + 1);

        if (_pageListData.length > 0) {
            let index = $.inArray(_dataId, _pageListData);
            if (index === 0) {
                $("#ButPrev").attr("disabled", "disabled");
            } else {
                $("#ButNext").removeAttr("disabled");
            }
            if (index === (_pageListData.length - 1)) {
                $("#ButNext").attr("disabled", "disabled");
            } else {
                $("#ButPrev").removeAttr("disabled");
            }
        }
    } else {
        $("#rec_total_rows").text("1");
        $("#rec_cur_row").text("1");
    }
    _InstancePageHeader = new MyPageHeader(_dataId, 0, 0, _pageStatus, _pageListData,
            "/purchase/po/list.html",
            "/purchase/po/header/fetchByKey.html",
            "/purchase/po/header/save.html",
            "/purchase/po/export.html",
            "/purchase/po/print.html");
    _InstancePageLines = new MyPageLines();
    _InstancePageLinesMrpHeader = new MyPageLinesMrpHeader();
    _InstancePageLinesMrpLines = new MyPageLinesMrpLines();
    _InstancePageLinesMrpFeedingHeader = new MyPageLinesMrpFeedingHeader();
    _InstancePageLinesMrpFeedingLines = new MyPageLinesMrpFeedingLines();

    window.laydate.render({
        elem: '#SignedDate',
        theme: '#393D49',
        trigger: 'click'
    });
    window.laydate.render({
        elem: '#OrderArrivalDate',
        theme: '#393D49',
        trigger: 'click'
    });

    $("#loading__indicator_02").hide();
    $("#loading__indicator_03").hide();
    $("#loading__indicator_04").hide();

    $("#tabPanelHeader").wxTabs({tabContent: "tabPanelContent"});

    // 设置调达表分页控制
    $("#wrapper__navbar_02").swPagination({
        link_string: '/?page={page_number}',
        max_page: null,
        paged: function (page) {
            $("abbr.page_indicator_block,#wrapper__navbar_02").attr("_msh_page", page);
            _InstancePageLinesMrpLines.FetchLinesForPage(page);
        }
    });
    // 设置补料单分页控制
    $("#wrapper__navbar_03").swPagination({
        link_string: '/?page={page_number}',
        max_page: null,
        paged: function (page) {
            $("abbr.page_indicator_block,#wrapper__navbar_03").attr("_msh_page", page);
            _InstancePageLinesMrpFeedingLines.FetchLinesForPage(page);
        }
    });
    // 设置采购订单明细分页控制
    $("#wrapper__navbar_04").swPagination({
        link_string: '/?page={page_number}',
        max_page: null,
        paged: function (page) {
            $("abbr.page_indicator_block,#wrapper__navbar_04").attr("_msh_page", page);
            _InstancePageLines.FetchLinesForPage(page);
        }
    });

    // 设置调达表明细表格排序字段
    $("#tabHeader21").wxTableSorter({
        sortList: [[1, 2], [3, 2], [4, 2]], // 第一个表示列的序号，第二个表示排序种类
        headers: {1: {sorter: false}, 3: {sorter: false}, 4: {sorter: false}},
        columnList: [[1, "P.StyleNo"],
            [2, "M.MaterialName"],
            [3, "M.MaterialCode"]],
        detailList: $("#tabData21"),
        sort: function (orderBy) {
            _InstancePageLinesMrpLines.SortTable(orderBy);
        }
    });
    $("#tabHeader22").wxTableSorter({
        sortList: [[2, 2]], // 第一个表示列的序号，第二个表示排序种类
        headers: {2: {sorter: false}},
        columnList: [[1, "MRPL.MaterialColourName"]],
        detailList: $("#tabData22"),
        sort: function (orderBy) {
            _InstancePageLinesMrpLines.SortTable(orderBy);
        }
    });
    // 设置补料单明细表格排序字段
    $("#tabHeader31").wxTableSorter({
        sortList: [[0, 2], [1, 2], [2, 2]], // 第一个表示列的序号，第二个表示排序种类
        headers: {0: {sorter: false}, 1: {sorter: false}, 2: {sorter: false}},
        columnList: [[1, "MRPH.BillNo"], [2, "M.MaterialName"], [3, "M.MaterialCode"]],
        detailList: $("#tabData31"),
        sort: function (orderBy) {
            _InstancePageLinesMrpFeedingLines.SortTable(orderBy);
        }
    });
    $("#tabHeader32").wxTableSorter({
        sortList: [[1, 2]], // 第一个表示列的序号，第二个表示排序种类
        headers: {1: {sorter: false}},
        columnList: [[1, "MRPL.MaterialColourName"]],
        detailList: $("#tabData32"),
        sort: function (orderBy) {
            _InstancePageLinesMrpFeedingLines.SortTable(orderBy);
        }
    });
    // 设置订单明细表格排序字段
    $("#tabHeader41").wxTableSorter({
        sortList: [[3, 2], [4, 2], [5, 2]], // 第一个表示列的序号，第二个表示排序种类
        headers: {3: {sorter: false}, 4: {sorter: false}, 5: {sorter: false}},
        columnList: [[1, "L.StyleNo"],
            [2, "M.MaterialCode"],
            [3, "M.MaterialName"]],
        detailList: $("#tabData41"),
        sort: function (orderBy, index) {
            switch (index) {
                // 按款号
                case 0:
                    orderBy = orderBy + ", COALESCE(L.ProductColourName,''), M.MaterialCode, COALESCE(L.MaterialColourName,''), COALESCE(L.Specification,''), L.UpdatedDate DESC";
                    break;
                    // 按料号
                case 1:
                    orderBy = orderBy + ", L.StyleNo, COALESCE(L.ProductColourName,''), COALESCE(L.MaterialColourName,''), COALESCE(L.Specification,''), L.UpdatedDate DESC";
                    break;
                    // 按料名
                case 2:
                    orderBy = orderBy + ", L.StyleNo, COALESCE(L.ProductColourName,''), COALESCE(L.MaterialColourName,''), COALESCE(L.Specification,''), L.UpdatedDate DESC";
                    break;
            }
            _InstancePageLines.SortTable(orderBy);
        }
    });
    $("#tabHeader42").wxTableSorter({
        sortList: [[1, 2]], // 第一个表示列的序号，第二个表示排序种类
        headers: {1: {sorter: false}},
        columnList: [[1, "L.MaterialColourName"]],
        detailList: $("#tabData42"),
        sort: function (orderBy, index) {
            switch (index) {
                case 0:
                    orderBy = orderBy + ", L.StyleNo, COALESCE(L.ProductColourName,''), M.MaterialCode, COALESCE(L.Specification,''), L.UpdatedDate DESC";
                    break;
            }
            _InstancePageLines.SortTable(orderBy);
        }
    });
    SetSearchWnd();

    // 用于导出excel文件
    $("#export_iframe").remove();
    let $iFrame = $('<iframe id="export_iframe" name="_export_iframe" style="position:absolute; top:-9999px; left:-9999px" src="javascript:false"></iframe>');
    $("body").append($iFrame);
    let $form = $('<form id="export_form" name ="_export_form" method="POST" action ="" target="_export_iframe" style="position:absolute; top:-1200px; left:-1200px"></form>');
    $('<input type="hidden" id="ExportPoHeaderId" name="_ExportPoHeaderId" value="" />').appendTo($form);
    $("body").append($form);
    // 监听iframe回调（submit()后设置iFrame加载完成事件，用于获取表单提交成功后的结果,iFrame.load(loadFunc());）
    $iFrame.on("load", function () {
        let contentWin = document.getElementById("export_iframe").contentWindow;
        let backBodyText = contentWin.document.body.innerText;
    });

    _InstancePageHeader.OnPageLoad();
}

function SetSearchWnd() {
    $("div.search").unbind('keyup');

    let clazz = 'search--active';
    // 设置引入调达表明细的搜索
    let $search_02 = $('#search_02');
    // 搜索按钮
    $('#search_btn_02').on('click', function (event) {
        $search_02.addClass(clazz);
        $search_02.on(window.transitionProp, function (event) {
            $search_02.find('input').first().focus();
        });
    });
    // 搜索窗口关闭
    $('#search__form_butclose_02').on('click', function (event) {
        $search_02.removeClass(clazz);
    });
    // 搜索框回车直接进行搜索
    $("#search_02").bind('keyup', function (e) {
        let key = e.keyCode;
        if (key === 13) {
            $("#but_filter_02").click();
        }
    });
    // 设置引入补料单明细的搜索
    let $search_03 = $('#search_03');
    // 搜索按钮
    $('#search_btn_03').on('click', function (event) {
        $search_03.addClass(clazz);
        $search_03.on(window.transitionProp, function (event) {
            $search_03.find('input').first().focus();
        });
    });
    // 搜索窗口关闭
    $('#search__form_butclose_03').on('click', function (event) {
        $search_03.removeClass(clazz);
    });
    // 搜索框回车直接进行搜索
    $("#search_03").bind('keyup', function (e) {
        let key = e.keyCode;
        if (key === 13) {
            $("#but_filter_03").click();
        }
    });
    // 设置引入订单明细的搜索
    let $search_04 = $('#search_04');
    // 搜索按钮
    $('#search_btn_04').on('click', function (event) {
        $search_04.addClass(clazz);
        $search_04.on(window.transitionProp, function (event) {
            $search_04.find('input').first().focus();
        });
    });
    // 搜索窗口关闭
    $('#search__form_butclose_04').on('click', function (event) {
        $search_04.removeClass(clazz);
    });
    // 搜索框回车直接进行搜索
    $("#search_04").bind('keyup', function (e) {
        let key = e.keyCode;
        if (key === 13) {
            $("#but_filter_04").click();
        }
    });
}

// 画面大小或者位置移动
function onPageResize() {
    let w = $(window).width();

    let wLeftList_2 = 930; // 调达表明细左边列表固定宽度
    $("#divH22").css({width: w - wLeftList_2 - 17});
    $("#divD22").css({left: -1, width: w - wLeftList_2 - 16});

    let wLeftList_3 = 860; // 补料单明细左边列表固定宽度
    $("#divH32").css({width: w - wLeftList_3 - 17});
    $("#divD32").css({left: -1, width: w - wLeftList_3 - 16});

    let wLeftList_4 = 589; // 订单明细左边列表固定宽度
    $("#divH42").css({width: w - wLeftList_4 - 17});
    $("#divD42").css({left: -1, width: w - wLeftList_4 - 16});

    over = 1;
}

//-----------------------------------------------------------------------------
// 验证函数
//-----------------------------------------------------------------------------
$.validator.setDefaults({
    ignore: 'hidden, [reaonly=readonly]'
});
$.validator.addMethod("valueNotEquals", function (value, element, arg) {
    return arg !== value;
}, "Value must not equal arg.");
$(function () {
    $("#form_data").validate({
        // Step 1：设置验证规则和错误消息
        rules: {
            _PoNo: "required",
            _BillTypeId: {
                valueNotEquals: "-1",
                required: true
            },
            _SupplierName: "required",
            _SignedDate: "required",
            _OrderArrivalDate: "required",
            _TermsOfPayment: "required",
            _PurchasedByName: "required",
            _CurrencyName: "required",
            _TaxRateText: "required",
            _EnterpriseName: "required"
        },
        messages: {
            _PoNo: "请填写采购合同号。",
            _BillTypeId: {
                valueNotEquals: "请选择合同类型。",
                required: "请选择合同类型。"
            },
            _SupplierName: "请填写供应商。",
            _SignedDate: "请填写下单日期。",
            _OrderArrivalDate: "请填写到货日期。",
            _TermsOfPayment: "请填写付款条款。",
            _PurchasedByName: "请填写采购担当。",
            _CurrencyName: "请填写币种。",
            _TaxRateText: "请填写税率。",
            _EnterpriseName: "请填写接单贸易公司。"
        },
        // Step 2：设置验证触发事件
        onclick: false,
        onfocusout: false,
        onfocusin: false,
        onkeyup: false,
        onkeydown: false,
        focusInvalid: false,
        // Step 3：设置错误信息提示
        showErrors: window.showErrors  //使用自定义的错误显示方法
    });
});

// 清除料号错误
function ClearGridMaterialNoError() {
    $('#tabData41 tbody').find("tr").each(function (index) {
        $(this).find('td').eq(4).attr('title', '');
        $(this).find('td').eq(4).removeClass("error");
    });
}